package com.king.juc.n8.threadpooldemo.forkjoindemo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RecursiveTask;

/**
 * 1~n 之间整数的和
 * @author king
 * @date 2020/12/12 20:39
 */
@Slf4j(topic = "c.MyTask")
public class MyTask extends RecursiveTask<Integer> {
    private int n;

    public MyTask(int n) {
        this.n = n;
    }

    @Override
    protected Integer compute() {
        if (1 == n){
            log.debug("join() {}", n);
            return 1;
        }

        // 拆分, 让一个线程去执行此任务
        MyTask t = new MyTask(n - 1);
        t.fork();
        log.debug("fork() {} + {}", n, t);

        // 获取任务结果并返回
        log.debug("join() {} + {} = {}", n, t, n + t.join());
        return n + t.join();
    }
}
